<!--
 * @Descripttion: 添加/更改方案
 * @version:
 * @Author: lehaixia
 * @Date: 2022-10-25 18:44:43
 * @LastEditors: lehaixia
 * @LastEditTime: 2022-11-28 13:59:34
-->
<template>
  <div class="content">
    <ComHeader :title="title" @get-height="handleHeadHeight" />
    <div class="page-container" style="background:#F8F8FA">
      <div class="page-search" :style="{'top':headHeight+'px'}">
        <SearchInput v-model="searchForm.keyword" :icon-right="false" placeholder="请输入方案名称" class="search" @search="handleSearch" @enter="handleSearch" />
      </div>
      <!-- 'list':schemeList.length>0,  -->
      <List
        ref="list"
        class="list"
        :class="{'pb-48': isHaveScheme}"
        :finished.sync="finished"
        :reset-fun="resetData"
        :load="load"
        :refresh="load"
        :default-active="true"
      >
        <div class="items">
          <div
            v-for="(v,i) in schemeList"
            :key="i"
            :class="[{'item-seleted': v.designId === formData.schemeId},'item', schemeList.length % 2 === 0 ? 'even-item':'odd-item']"
            @click="handleSelectScheme(v)"
          >
            <van-image :src="v.coverPic |filterURL" width="100%" height="100px" fit="cover">
              <error-pic slot="error" />
            </van-image>
            <span>{{ v.name }}</span>
          </div>
        </div>
      </List>
      <div v-if="isHaveScheme && formData.schemeId" class="button-outer">
        <van-button type="primary" class="info-button" @click="submitForm">确定</van-button>
      </div>
    </div>

    <van-popup v-if="!isHaveScheme" v-model="showPicker" position="bottom" class="popup">
      <van-datetime-picker
        v-model="formData.inviteToStoreTime"
        type="date"
        title="预约确认方案日期"
        :min-date="minDate"
        :show-toolbar="false"
        :formatter="formatter"
        item-height="53px"
        @confirm="onConfirm"
      >
        <template #columns-top>
          <div class="popup-top">
            <div class="popup-top-title"><span>预约确认方案日期</span></div>
            <img class="cancel" :src="ic_popup_quit" @click="showPicker = false">
          </div>
        </template>
        <template #columns-bottom>
          <div class="button-box">
            <van-button type="primary" class="info-button" @click="submitForm">确定</van-button>
          </div>
        </template>
      </van-datetime-picker>
    </van-popup>
  </div>
</template>
<script>
import ic_popup_quit from '@/assets/category/ic_popup_quit@2x.png'
import { bindScheme, queryMySchemeByPage } from '@/apis/optyCategory'
import { json2FormData } from '@/utils'
import SearchInput from '@/components/SearchInput'
import List from '@/components/List'
import ErrorPic from '@/components/ErrorPic'
import { ImagePreview } from 'vant'
import { bus } from '@/utils/bus'

export default {
  name: 'SchemeAdd',
  components: {
    SearchInput, List, ErrorPic
  },
  data() {
    const time = new Date()
    return {
      ic_popup_quit,
      headHeight: 50,
      schemeList: [],
      finished: false, // 列表是否加载完成
      showPicker: false,
      minDate: time, // 限制最小时间
      isHaveScheme: false,
      searchForm: {
        keyword: '', // 方案名搜索
        orderTypes: '' // 品类
      },
      formData: {
        schemeId: '',
        optyCategoryIds: [],
        inviteToStoreTime: time
      },
      submiting: false
    }
  },
  computed: {
    title() {
      return this.isHaveScheme ? '变更方案' : '添加方案'
    }
  },
  created() {
    const { id, type = '', isHaveScheme = 0 } = this.$route.query
    this.optyCategoryId = id
    this.isHaveScheme = isHaveScheme === '1' // 是否为变更方案页面

    this.$set(this.searchForm, 'orderTypes', type)
    this.$set(this.formData, 'optyCategoryIds', id && [id] || [])
  },
  methods: {
    handleHeadHeight(h) {
      this.headHeight = h
    },
    // 查询关键字
    handleSearch(value) {
      this.searchValue = value
      // console.log('查询关键字', value)
      this.resetPageData()
    },
    resetPageData() {
      if (this.$refs.list) {
        this.$refs.list.resetPageData()
      }
    },
    load(page, rows) {
      const data = json2FormData({
        pageFlag: true,
        paramsRaw: JSON.stringify(this.searchForm),
        page: page,
        rows: rows,
        sort: 'createTimeStr',
        order: 'desc'
      })
      return queryMySchemeByPage(data).then(res => {
        const records = res.data.records || []
        this.schemeList.push(...records)
        if (this.schemeList.length >= res.data.total) {
          this.finished = true
        }
      })
    },
    resetData() {
      this.schemeList = []
    },
    // 选中方案
    handleSelectScheme(v) {
      if (!this.isHaveScheme) this.showPicker = true

      this.$set(this.formData, 'schemeId', v.designId)
    },
    // 查看图片
    clickPreviewHandle(i) {
      ImagePreview({
        images: this.schemeList.map(e => this.$formatURL(e.coverPic)),
        startPosition: i || 0
      })
    },
    // 日期选择器
    onConfirm(value) {
      // console.log(this.$parseTime(value, '{y}-{m}-{d}'))
      const inviteToStoreTime = value && this.$parseTime(value, '{y}-{m}-{d}') || ''
      this.$set(this.formData, 'inviteToStoreTime', inviteToStoreTime)
      this.showPicker = false
    },
    // 格式化年月日显示
    formatter(type, val) {
      if (type === 'year') {
        return `${val}年`
      } else if (type === 'month') {
        return `${val}月`
      } else if (type === 'day') {
        return `${val}日`
      }
      return val
    },
    // 提交表单处理
    submitForm() {
      if (this.submiting) return
      const url = this.isHaveScheme ? 'changeScheme' : 'bindScheme'
      const { inviteToStoreTime, schemeId, optyCategoryIds } = this.formData
      if (!schemeId) {
        this.$toast('请先选择方案')
        return
      }
      let data = {}
      if (!this.isHaveScheme) {
        data = { ...this.formData, inviteToStoreTime: this.$parseTime(inviteToStoreTime) }
      } else {
        data = { schemeId, optyCategoryIds }
      }

      this.submiting = true
      bindScheme(url, data).then(res => {
        this.submiting = false
        if (res.success === 1) {
          this.$router.go(-1)
          bus.$emit('refreshCustomerItem', {
            title: '方案',
            type: 'scheme',
            isRefreshCategory: !this.isHaveScheme
          })
        }
      }).catch(() => {
        this.submiting = false
      })
      this.showPicker = false
    }
  }
}
</script>
<style lang="less" scoped>
 .page-search {
    position: fixed;
    top: 46px;
    left: 0;
    width: 100%;
    z-index: 999;
    background: #F8F8FA;

    .search {
      ::v-deep .van-field__control::-webkit-input-placeholder {
        font-size: 14px;
        font-weight: 400;
        color: #B5B7C4;
        line-height: 20px;
      }
    }
  }
  .pb-48 {
    padding-bottom: 48px;
  }
  .list {
    padding-top: 76px;
  }
  .items {
    display: flex;
    flex-flow: wrap;
    justify-content: space-between;
    padding: 0 16px;

    .item {
      --width: calc(50vw - 22px);
      width: var(--width);
      position: relative;
      overflow: hidden;
      background: #fff;
      border-radius: 12px;
      margin-bottom: 17px;

      span {
        font-size: 12px;
        font-weight: 400;
        color: #3C4458;
        line-height: 17px;
        display: block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        padding: 10px;
      }

    }
    .item-seleted {
      border: 1px solid #16BC83;
    }
    .even-item {
      &:nth-last-of-type(1), &:nth-last-of-type(2) {
        margin-bottom: 0 !important;
      }
    }
    .odd-item {
      &:nth-last-of-type(1) {
        margin-bottom: 0 !important;
      }
    }
  }

  .popup {
    background: #FFFFFF;
    border-radius: 24px 24px 1px 1px;
    .popup-top {
      position: relative;
      .popup-top-title {
        display: flex;
        align-items: center;
        justify-content: center;
        padding-top: 24px;

        span {
          font-size: 18px;
          font-weight: 600;
          color: #343640;
          line-height: 25px;
        }
      }

      .cancel {
        width: 20px;
        height: 20px;
        position: absolute;
        right: 16px;
        top: 10px;
      }
    }

    /deep/ .van-picker__columns {
      width: calc(100vw - 70px);
      margin: 0 auto;
      .van-picker-column__item {
        font-size: 16px;
        font-weight: 400;
        color: #A8B0C5;
        line-height: 22px;
      }

      .van-picker-column__item--selected {
        font-size: 18px;
        font-weight: 600;
        color: #343640;
        line-height: 25px;
      }

      .van-hairline--top-bottom::after, .van-hairline-unset--top-bottom::after {
        border-width: 2px 0 !important;
      }

      [class*=van-hairline]::after {
        border: 0 solid #16BC83;
      }
    }

    .button-box {
      padding: 40px 16px;
      height: 48px;
      .info-button {
        width: 100%;
        background: linear-gradient(270deg, #009E77 0%, #20CE92 100%);
        border-radius: 12px;
        font-size: 16px;
        font-weight: 600;
        color: #FFFFFF;
        height: 100%;
        line-height: 22px;
        /deep/ .van-button--disabled {
          opacity: .4;
        }
      }
    }
  }
  .button-outer {
    position: fixed;
    bottom: 0;
    width: calc(100vw - 32px);
    height: 58px;
    left: 16px;
    .info-button {
      width: 100%;
      background: linear-gradient(270deg, #009E77 0%, #20CE92 100%);
      border-radius: 12px;
      font-size: 16px;
      font-weight: 600;
      color: #FFFFFF;
      line-height: 22px;
      height: 48px;
      /deep/ .van-button--disabled {
        opacity: .4;
      }
    }
  }
</style>
